<template>
  <div class="geographic">
    <p v-if='isReadOnlyPage' class="mb5">{{ strValue }}</p>
    <a-row class="control_view mb10" :gutter="20" v-show="!isReadOnlyPage">
      <a-col :span="12" class="control_item">
        <a-input v-model="address" @pressEnter="search"></a-input>
        <a-button @click="search" class="ml10">搜索</a-button>
      </a-col>
      <a-col :span="12">
        <a-input readonly :value="pointText"></a-input>
      </a-col>
    </a-row>
    <baidu-map class="bm_view" ak="preLAzicd3eVQdDs7Pifbajl" @ready="handler">
    </baidu-map>
  </div>
</template>

<script>

import BaiduMap from 'vue-baidu-map/components/map/Map.vue'

let BMapClass
let mapInstace
export default {
  name: 'Geographic',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: ['value', 'required', 'isReadOnlyPage', 'isDisabled'],
  components: { BaiduMap },
  data () {
    return {
      address: '',
      point: {},
      marker: ''
    }
  },
  computed: {
    strValue () {
      if (!this.value) {
        return ''
      } else {
        return `经度：${this.value.longitude}，纬度：${this.value.latitude}`
      }
    },
    pointText () {
      if (this.point.longitude) {
        return `经度：${this.point.longitude}，纬度：${this.point.latitude}`
      } else {
        return ''
      }
    }
  },
  mounted () {
    setTimeout(() => {
      console.log('mounted', this.value)
      if (this.value && this.value.longitude && this.value.latitude) {
        const valuePoint = new BMapClass.Point(this.value.longitude, this.value.latitude)
        mapInstace.centerAndZoom(valuePoint, 12)
        this.setPoint({ point: valuePoint })
      } else {
        var geolocation = new BMapClass.Geolocation()
        geolocation.getCurrentPosition((r) => {
          console.log('getCurrentPosition', r)
          mapInstace.centerAndZoom(r.point, 12)
        }, { enableHighAccuracy: true })
      }
    }, 300)
  },
  methods: {
    handler ({ BMap, map }) {
      BMapClass = BMap
      mapInstace = map

      map.enableScrollWheelZoom()
      map.enableContinuousZoom()

      map.addEventListener('click', this.setPoint)
    },
    search () {
      var local = new BMapClass.LocalSearch(mapInstace, {
        renderOptions: { map: mapInstace }
      })
      local.search(this.address)
    },
    setPoint (e) {
      console.log('setPoint,', e)
      const marker = new BMapClass.Marker(e.point)
      mapInstace.removeOverlay(this.marker)
      mapInstace.addOverlay(marker)
      this.marker = marker
      this.point = { longitude: e.point.lng, latitude: e.point.lat }
      this.$emit('change', this.point)
    }
  }
}
</script>
<style lang="stylus" scoped>
.geographic
  .control_view
    .control_item
      display flex
  .bm_view
    width 100%
    height 400px
</style>
